<?php

namespace app\index\controller;

use think\Db as userDB;
use think\Log;
use think\Cache;


class User extends Common{

    public $datas;

    /**
     * 新增名片
     */
    public function addUser(){
        /**
         * userName              真实姓名
         * eUserName             英文名
         * institute             机构
         * subject               学科
         * researchDirection     研究方向
         * userDetail            个人简介
         * phone                 手机号
         * userImg               头像
         * email                 邮箱
         * address               联系地址
         * openId                微信openid
         * unionid               微信unionid
         * userNo                userNo
         * jobTitle              职称
         */
        $this->datas = $this->params;

        $this->addUserService();
    }


    private function addUserService(){

        if(!empty($this->datas['unionId'])){
            //通过unionId查询
            $sql = "select * from user where status in (0,1) and union_id = '".$this->datas['unionId']."'";
            $res = userDB::query($sql);

            if(!empty($res)){
                $this->returnMsg(9, '该账号已经注册过！');
            }
        }

        if(!empty($this->datas['userNo'])){
            //通过userNo查询
            $sql = "select * from user where status in (0,1) and user_no = '".$this->datas['userNo']."'";
            $res = userDB::query($sql);

            if(!empty($res)){
                $this->returnMsg(9, '该账号已经注册过！');
            }
        }
        


        $insertData = [];
        $insertData['user_name'] = $this->datas['userName'];
        $insertData['e_user_name'] = $this->datas['eUserName'];
        $insertData['institute'] = $this->datas['institute'];
        $insertData['subject'] = $this->datas['subject'];
        $insertData['research_direction'] = $this->datas['researchDirection'];
        $insertData['user_detail'] = $this->datas['userDetail'];
        $insertData['status'] = 0;
        if(!empty($this->datas['email'])){
            $insertData['email'] = $this->datas['email'];
        }
        if(!empty($this->datas['address'])){
            $insertData['address'] = $this->datas['address'];
        }
        if(!empty($this->datas['phone'])){
            $insertData['phone'] = $this->datas['phone'];
        }
        if(!empty($this->datas['userImg'])){
           $insertData['user_img'] = $this->datas['userImg'];
        }
        if(!empty($this->datas['openId'])){
            $insertData['open_id'] = $this->datas['openId'];
        }
        if(!empty($this->datas['unionId'])){
            $insertData['union_id'] = $this->datas['unionId'];
        }
        if(!empty($this->datas['userNo'])){
            $insertData['user_no'] = $this->datas['userNo'];
            $insertData['status'] = 1;
            $insertData['scholar_id'] = $this->datas['userNo'];
        }
        if(!empty($this->datas['jobTitle'])){
            $insertData['job_title'] = $this->datas['jobTitle'];
        }
        $insertData['create_time'] = date('Y-m-d H:i:s');
        $insertData['update_time'] = date('Y-m-d H:i:s');

        $userId = userDB::table('user')->insert($insertData, false, true);


        // 添加用户名片操作记录
        insert_user_log($userId, 2);

        $this->returnMsg(1, '操作成功！');
    }



    /**
     * 通过unionid查询名片信息
     */
    public function getUser(){
        /**
         * unionid                微信unionid
         */
        $this->datas = $this->params;

        $this->getUserService();
    }


    private function getUserService(){

        //通过openid查询
        $sql = "select id,user_name as userName,e_user_name as eUserName,institute,subject,research_direction as researchDirection"
            .",user_detail as userDetail,phone,user_img as userImg,email,address,open_id as openId,union_id as unionId,create_time as createTime,update_time as updateTime,status,user_no AS userNo,ifnull(job_title,'') as jobTitle"
            ." from user where status in (0,1) and union_id = '".$this->datas['unionId']."'";
        $res = userDB::query($sql);

        if(empty($res)){
            $this->returnMsg(9, '该微信未注册过！');
        }

        $this->returnMsg(1, '获取数据成功！',$res[0]);
    }


     /**
     *  修改名片(通过unionId)
     */
    public function updateUser(){
        /**
         * userName              真实姓名
         * eUserName             英文名
         * institute             机构
         * subject               学科
         * researchDirection     研究方向
         * userDetail            个人简介
         * phone                 手机号
         * userImg               头像
         * email                 邮箱
         * address               联系地址
         * openId                微信openid
         * unionId               微信unionId
         * jobTitle              职称
         */
        $this->datas = $this->params;

        $this->updateUserService();
    }


    private function updateUserService(){

       //通过openid查询
        $sql = "select * from user where status in (0,1) and union_id = '".$this->datas['unionId']."'";
        $res = userDB::query($sql);

        if(empty($res)){
            $this->returnMsg(9, '该微信未注册过！');
        }

        userDB::name('user')->where([
            'id'=>$res[0]['id']
        ])->update([
            'user_name'=>$this->datas['userName'],
            'e_user_name'=>$this->datas['eUserName'],
            'institute'=>$this->datas['institute'],
            'subject'=>$this->datas['subject'],
            'research_direction'=>$this->datas['researchDirection'],
            'user_detail'=>$this->datas['userDetail'],
            'phone'=>$this->datas['phone'],
            'user_img'=>$this->datas['userImg'],
            'email'=>$this->datas['email'],
            'address'=>$this->datas['address'],
            'open_id'=>$this->datas['openId'],
            'job_title'=>$this->datas['jobTitle'],
            'update_time'=>date('Y-m-d H:i:s')
        ]);

        $this->returnMsg(1, '操作成功！');
    }

    /**
     *  修改名片(通过userNo)
     */
    public function updateUserByUserNo(){
        /**
         * userName              真实姓名
         * eUserName             英文名
         * institute             机构
         * subject               学科
         * researchDirection     研究方向
         * userDetail            个人简介
         * phone                 手机号
         * userImg               头像
         * email                 邮箱
         * address               联系地址
         * userNo                userNo
         * jobTitle              职称
         */
        $this->datas = $this->params;

        $this->updateUserByUserNoService();
    }


    private function updateUserByUserNoService(){

       //通过openid查询
        $sql = "select * from user where status in (0,1) and user_no = '".$this->datas['userNo']."'";
        $res = userDB::query($sql);

        if(empty($res)){
            $this->returnMsg(9, '该账号未注册过！');
        }

        userDB::name('user')->where([
            'id'=>$res[0]['id']
        ])->update([
            'user_name'=>$this->datas['userName'],
            'e_user_name'=>json_encode($this->datas['eUserName']),
            'institute'=>$this->datas['institute'],
            'subject'=>$this->datas['subject'],
            'research_direction'=>json_encode($this->datas['researchDirection']),
            'user_detail'=>$this->datas['userDetail'],
            'phone'=>$this->datas['phone'],
            'user_img'=>$this->datas['userImg'],
            'email'=>$this->datas['email'],
            'address'=>$this->datas['address'],
            //'open_id'=>$this->datas['openId'],
            'job_title'=>$this->datas['jobTitle'],
            'update_time'=>date('Y-m-d H:i:s')
        ]);

        $this->returnMsg(1, '操作成功！');
    }


    /**
     * 通过编号查询名片信息
     */
    public function getUserById(){
        /**
         * id                名片编号
         */
        $this->datas = $this->params;

        $this->getUserByIdService();
    }


    private function getUserByIdService(){

        //通过id查询
        $sql = "select id,user_name as userName,e_user_name as eUserName,institute,subject,research_direction as researchDirection"
            .",user_detail as userDetail,phone,user_img as userImg,email,address,open_id as openId,union_id as unionId,create_time as createTime,update_time as updateTime,status,user_no AS userNo,ifnull(job_title,'') as jobTitle"
            ." from user where status in (0,1) and id = '".$this->datas['id']."'";
        $res = userDB::query($sql);

        if(empty($res)){
            $this->returnMsg(9, '该微信未注册过！');
        }

        $this->returnMsg(1, '获取数据成功！',$res[0]);
    }

    /**
     * 通过userNo查询名片信息
     */
    public function getUserByUserNo(){
        /**
         * userNo                userNo
         */
        $this->datas = $this->params;

        $this->getUserByUserNoService();
    }


    private function getUserByUserNoService(){

        //通过id查询
        $sql = "select id,user_name as userName,e_user_name as eUserName,institute,subject,research_direction as researchDirection"
            .",user_detail as userDetail,phone,user_img as userImg,email,address,open_id as openId,union_id as unionId,create_time as createTime,update_time as updateTime,status,user_no AS userNo,ifnull(job_title,'') as jobTitle"
            ." from user where status in (0,1) and user_no = '".$this->datas['userNo']."'";
        $res = userDB::query($sql);

        if(empty($res)){
            $this->returnMsg(9, '该账号未注册过！');
        }

        // 添加用户名片操作记录
        insert_user_log($res[0]['id'], 1);

        $this->returnMsg(1, '获取数据成功！',$res[0]);
    }


    /**
     * 名片激活
     */
    public function activationUser(){
        /**
         * id                名片编号
         * scholarId         学者编号
         */
        $this->datas = $this->params;

        $this->activationUserService();
    }


    private function activationUserService(){
        userDB::name('user')->where([
            'id'=>$this->datas['id']
        ])->update([
            'scholar_id'=>$this->datas['scholarId'],
            'status'=>1,
            'update_time'=>date('Y-m-d H:i:s')
        ]);

        $this->returnMsg(1, '操作成功！');
    }

    /**
     * 名片注销
     */
    public function delUser(){
        /**
         * id                名片编号
         */
        $this->datas = $this->params;

        $this->delUserService();
    }


    private function delUserService(){
        userDB::name('user')->where([
            'id'=>$this->datas['id']
        ])->update([
            'status'=>0,
            'update_time'=>date('Y-m-d H:i:s')
        ]);

        $this->returnMsg(1, '操作成功！');
    }

    /**
     * 名片提问
     */
    public function addUserProblem(){
        /**
         * id                名片编号
         * problemType
         * problemContent
         * imgs
         */
        $this->datas = $this->params;

        $this->addUserProblemService();
    }


    private function addUserProblemService(){
        
        $insertData = [];
        $insertData['user_id'] = $this->datas['id'];
        $insertData['problem_type'] = $this->datas['problemType'];
        $insertData['problem_content'] = $this->datas['problemContent'];
        $insertData['imgs'] = $this->datas['imgs'];
        $insertData['status'] = 1;
        $insertData['create_time'] = date('Y-m-d H:i:s');
        $insertData['update_time'] = date('Y-m-d H:i:s');

        userDB::table('user_problem')->insert($insertData);

        $this->returnMsg(1, '操作成功！');
    }




    /**
     * 未加入名片夹名片列表
     */
    public function getUserPage(){
        /**
         * userId           名片编号
         * pageNo           页码
         * pageSize         每页条数
         */
        $this->datas = $this->params;

        $this->getUserPageService();
    }


    private function getUserPageService(){

        $pageNo = 1;
        $pageSize = 10;

        if(!empty($this->datas['pageNo'])){
            $pageNo = $this->datas['pageNo'];
        }

        if(!empty($this->datas['pageSize'])){
            $pageSize = $this->datas['pageSize'];
        }

        $pageNo = ($pageNo - 1) * $pageSize;


        $sql = "SELECT u.id AS id,u.user_name AS userName,u.user_img AS userImg,u.institute AS institute,ifnull(u.job_title,'') AS jobTitle,ifnull(u.e_user_name,'') AS eUserName,ifnull(u.subject,'') AS subject,ifnull(u.research_direction,'') AS researchDirection,ifnull(u.user_detail,'') AS userDetail  FROM user u WHERE u. STATUS = 1 AND u.id != ".$this->datas['userId']." AND u.id NOT IN (SELECT buddy_user_id FROM user_buddy b WHERE b. STATUS = 1 AND b.user_id = ".$this->datas['userId'].") ORDER BY u.id limit ".$pageNo.",".$pageSize;
        $res = userDB::query($sql);

        $countsql = "SELECT count(1) as num FROM user u WHERE u. STATUS = 1 AND u.id != ".$this->datas['userId']." AND u.id NOT IN (SELECT buddy_user_id FROM user_buddy b WHERE b. STATUS = 1 AND b.user_id = ".$this->datas['userId'].")";
        $count = userDB::query($countsql);


        $this->returnMsg(1, '获取数据成功！', $res, $count[0]["num"]);
    }


    /**
     * 分享名片
     */
    public function shareUser(){
        /**
         * userId           名片编号
         */
        $this->datas = $this->params;

        $this->shareUserService();
    }


    private function shareUserService(){

        // 添加用户名片操作记录
        insert_user_log($this->datas['userId'], 4);

        $this->returnMsg(1, '操作成功！');
    }


    /**
     * 移动端查学者
     */
    public function findScholarByUserId(){
        $this->datas = $this->params;

        $pageNo = 1;
        $pageSize = 10;

        if(!empty($this->datas['pageNo'])){
            $pageNo = $this->datas['pageNo'];
        }

        if(!empty($this->datas['pageSize'])){
            $pageSize = $this->datas['pageSize'];
        }

        $pageNo = ($pageNo - 1) * $pageSize;


        $sql = "select a.id,a.scholar_name,a.institute,a.professional_title,a.key_words,a.avatar_path,b.id user_id,IFNULL(c.buddy_user_id,'0') isfocus from scholar a"
                ." left join user b on a.kid = b.user_no left join (SELECT * from user_buddy WHERE status = '1' and user_id = '".$this->datas['userId']."') c "
                ." on b.id = c.buddy_user_id WHERE scholar_name like '%".$this->datas['keyWords']."%' or key_words like '%".$this->datas['keyWords']."%'  limit ".$pageNo.",".$pageSize;
        $res = userDB::query($sql);

        $countsql = "select count(1) num from scholar a"
                    ." left join user b on a.kid = b.user_no left join (SELECT * from user_buddy WHERE status = '1' and user_id = '".$this->datas['userId']."') c "
                    ." on b.id = c.buddy_user_id WHERE scholar_name like '%".$this->datas['keyWords']."%' or key_words like '%".$this->datas['keyWords']."%'";
        $count = userDB::query($countsql);


        $this->returnMsg(1, '获取数据成功！', $res, $count[0]["num"]);
    }








}